import React, { Component, PureComponent } from "react";
import { actions } from "mirrorx";
import { InputNumber, Select, FormControl, Table, Message } from 'tinper-bee';
import Radio from 'bee-radio';
import FormList from 'components/FormList';
import { getValidateFieldsTrim } from "utils";
import moment from "moment";
import DatePicker from "bee-datepicker";
import PopDialog from 'components/Pop';
import FormError from 'components/FormError';
import RefComponent from 'components/RefComponent';
import { onHandleChildObj, initValueString, resetOfferRefCommon,CalcuParmForRef,onChangeSelect} from 'utils';

import zhCN from "rc-calendar/lib/locale/zh_CN";
import './index.less'

const FormItem = FormList.Item;
const { Option } = Select;
const { YearPicker } = DatePicker;
const format = "YYYY-MM-DD";
const formatYYYY = "YYYY";
let titleArr = ["新增", "修改", "详情"];

class PopupModal extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            btnFlag: 0,
            cancelFlag: false,
            refStateParam: {}
        }
    }

    componentWillReceiveProps(nextProps) {
        // if(nextProps.btnFlag == 0) {
        //     this.props.form.resetFields();
        // }
    }

    /**
     * 关闭Modal
     */
    onCloseEdit = (values) => {
        if(values.target || values.btnClick) values = null;
        this.props.onCloseEdit(values);
    }

    /**
     * 提交表单信息
     */
    onSubmitEdit = () => {
        let _this = this;
        let { currentIndex, list, childType, btnFlag, customerId } = this.props;

        _this.props.form.validateFields((err, _values) => {
            let values = getValidateFieldsTrim(_values);
            //放开校验
            //处理保存的数据
            let data;
            data = onHandleChildObj(values, btnFlag, err);
            values = data.values;
            err = data.err;
            if (err) {

                Message.create({ content: '数据填写错误', color: 'warning', duration: 10 });
            } else {
                if (err) {
                    Message.create({ content: '必填项未填', color: 'warning', duration: 10  });
                } else {
                    values.customerId = customerId;
                    let dealSingleList = list[currentIndex] || {};
                    if (btnFlag == 1) {
                        dealSingleList = Object.assign({}, dealSingleList, values);
                        if (dealSingleList.id) {
                            dealSingleList.persistStatus = "upd";
                        } else {
                            dealSingleList.persistStatus = "new"
                        }
                    } else {
                        dealSingleList = values;
                        dealSingleList.persistStatus = "new";
                    }
                    _this.onCloseEdit(dealSingleList);
                }
            }
        });
    }

    /**
     *
     * @description 底部按钮是否显示处理函数
     * @param {Number} btnFlag 为页面标识
     * @returns footer中的底部按钮
     */
    onHandleBtns = (btnFlag) => {
        let _this = this;
        let btns = [

            {
                label: '取消',
                fun: this.onCloseEdit,
                shape: 'border'
            },
            {
                label: '确定',
                fun: _this.onSubmitEdit,
                colors: 'primary'
            },
        ];

        if (btnFlag == 2) {
            btns = [];
        }
        return btns;
    }

    //拼接下级级联的上级参数值
    calcuParm = (item, data, fieldName, childType) => {
        let { refStateParam } = this.state;
        let tempParam = {};
        let cascadeName = item.cascadeName;
        // let param = item.param;
        // if(!param)  param={};
        if (!cascadeName) return param;
        //待优化 先取一个级联参数
        let paramName = cascadeName[0];

        tempParam[paramName] = data[0] && data[0].refpk || null;
        //param 配置数据里的固定参数
        //tempParam 依赖字段计算出来的参数
        //tempParam = Object.assign({}, param, tempParam);
        let _thisParmField = `${fieldName}_${childType}`;
        refStateParam[_thisParmField] = tempParam;
        this.setState({ refStateParam });
    }

    //拼接下级级联的上级参数值
    addressCalcuParm = (pk, fieldName) => {
        let { childType } = this.props;
        let { refStateParam } = this.state;
        let tempParam = {};
        let paramName = "EQ_parent.id";
        // let param = item.param;

        tempParam[paramName] = pk || null;
        //param 配置数据里的固定参数
        //tempParam 依赖字段计算出来的参数
        //tempParam = Object.assign({}, param, tempParam);
        let _thisParmField = `${fieldName}_${childType}`;
        refStateParam[_thisParmField] = tempParam;
        this.setState({ refStateParam });
    }
    //重置下级级联参照
    resetOfferRef = (item, childType, childRowData) => {
        if (!item.offers) return;
        let param = {}
        param[item.offers] = null;
        //重置级联下级参照值
        this.props.form.setFieldsValue(param);
    }

    onInitSelectDataList = () => {
        let { childType, btnFlag, dataHeader, list, currentIndex } = this.props;
        let initSelectDataList = {};
        if (childType == "mrjtCustomerAddressList" && btnFlag == "0") {
            let {
                countryId,
                countryName,
                provinceId,
                provinceName,
                cityId,
                cityName,
                countyId,
                countyName
            } = onHandleChildObj(dataHeader).values || {}
            initSelectDataList = {
                countryId,
                countryName,
                provinceId,
                provinceName,
                cityId,
                cityName,
                countyId,
                countyName
            }
            if (countyId) {
                this.addressCalcuParm(countyId, "countyId");
            } else if (cityId) {
                this.addressCalcuParm(cityId, "cityId");
            } else if (provinceId) {
                this.addressCalcuParm(provinceId, "provinceId");
            }
            return initSelectDataList;
        } else {
            return list[currentIndex] || {};
        }
    }

    // setBankCategoryCode = (data) => {
    //     if (!data[0]) return;
    //     let param = { bankCategoryCode: data[0].bankCategoryCode, bankCategoryName: data[0].bankCategoryName };
    //     //param["pkCurrtypeName"] = data[0].currencyName;
    //     //重置级联下级参照值
    //     this.props.form.setFieldsValue(param);
    // }

    renderFunc = () => {
        let { ColumnsData, list, currentIndex, childType, selectDataList = {}, btnFlag, dataHeader } = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        //let childRowData = this.initSearchValue();
        //先不做主信息带到明细
        //let childRowData = this.onInitSelectDataList() || {};

        let childRowData = list[currentIndex] || {};

        if (childType == "mrjtCustomerAddressList" && btnFlag == "0") {
            childRowData = {
                countryId: "0001Z010000000079UJJ",
                countryName: "中国"
            }
        }

        if (childType == "mrjtCustomerContactList" && btnFlag == "0") {
            let { personId, personName } = this.props.personData;
            childRowData = {
                "personId": personId,
                "personName": personName
            }
        }

        if (childType == "mrjtCustomerAccountList" && btnFlag == "0") {
            childRowData = {
                "accountName": dataHeader.name,
                "currencyId": "1002Z0100000000001K1",
                "currencyName": "人民币",
            }
        }

        if (childType == "mrjtCustomerMaterialsUsedList" && btnFlag == "0") {
            let { departmentId, departmentName } = this.props.personData;
            childRowData = {
                departmentId: departmentId,
                departmentName: departmentName,
            }
        }

        let dom = [];
        let self = this;
        let required;
        ColumnsData.forEach((item, index) => {
            required = item.required;
            switch (item.type) {
                case 'FormControl':
                    dom.push(<FormItem
                        className="time"
                        key={`${item.enname}${index}`}
                        FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                        required={item.required}
                        label={item.zhname}
                    >
                        <FormControl key={`${item.enname}${index}`} disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] || "",
                                rules: [{
                                    required: required,
                                    message: "请输入",
                                },
                                {
                                    pattern: item.pattern || /^[\w\W]{0,100}$/,
                                    message: <span>超长度</span>,
                                }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'InputNumber':
                    dom.push(<FormItem
                        className="time"
                        key={`${item.enname}${index}`}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                        label={item.zhname}
                    >
                        <InputNumber toThousands={true}  key={`${item.enname}${index}`} iconStyle="one" max={item.max}
                            min={item.min || 0} step={item.step || 1} precision={item.precision || 0} disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: (typeof childRowData[item.enname]) === "number" ? childRowData[item.enname] : 0,
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'DatePicker':
                    dom.push(<FormItem
                        className="time"
                        key={`${item.enname}${index}`}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                        label={item.zhname}
                    >
                        <DatePicker key={`${item.enname}${index}`} className='form-item' format={item.format || format} disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] && moment(childRowData[item.enname]) || moment(),
                                validateTrigger: 'onBlur',
                                rules: [{ required: required, message: '请选择', }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'RefComponent':
                    dom.push(<FormItem
                        className="time"
                        key={`${item.enname}${index}`}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                        label={item.zhname}
                    >
                        <RefComponent
                            key={`${item.enname}${index}`}
                            disabled={!item.edit}
                            constparam={item.param}
                            aliasparam={self.state.refStateParam}
                            aliasfieldName={item.alias}
                            title={item.zhname}
                            refName={item.refname}
                            childType={childType}
                            fieldName={item.enname}
                            clearMatchData={this.clearMatch}
                            rules={[
                                {
                                    required: required,
                                    message: '请选择',
                                    pattern: item.required && /[^{"refname":"","refpk":"","refcode":""}|{"refpk":"","refname":"","refcode":""}]/
                                }
                            ]}
                            initialValue={initValueString(childRowData[item.showname], childRowData[item.enname], item.required)}
                            refTableOnClickSave={(refName, fieldName, data) => {
                                if (item.offers) {
                                    self.resetOfferRef(item, childType, childRowData);
                                }
                                if (item.cascadeName && data[0]) {
                                    //item 配置数据
                                    //data 参照返回数据
                                    //fieldName 参照Id字段
                                    //childType 字表所属字段
                                    CalcuParmForRef(item, data[0].refpk,self,true);
                                }
                                if (item.relation && data[0]) {
                                    resetOfferRefCommon(self, item.relation, data);
                                }
                            }}
                            form={self.props.form}
                        />
                    </FormItem>);
                    break;
                case 'Select':
                    let options = selectDataList[item.code] || item.options;
                    dom.push(<FormItem
                        className="time"
                        key={`${item.enname}${index}`}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${item.codename}`)} />}
                        label={item.zhname}
                    >
                        <Select
                            disabled={!item.edit}
                            onSelect={(value, props) => { onChangeSelect(self, props, item) }}
                            {
                            ...getFieldProps(`${item.codename}`, {
                                initialValue: childRowData[item.codename] || "",
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            })
                            }
                        >
                            <Option value="">请选择</Option>
                            {
                                options && options.map((item, index) => {
                                    return (
                                        <Option key={index} id={item.id} value={item.code}>{item.name}</Option>
                                    )
                                })
                            }

                        </Select>
                        <FormControl className="hide"
                            {...getFieldProps(`${item.showname}`, {
                                initialValue: childRowData[item.showname] || "",
                            })}
                        />
                        <FormControl className="hide"
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] || "",
                            })}
                        />
                    </FormItem>);
                    break;
                case 'Radio':
                    dom.push(<FormItem
                        className={item.hideVisible && 'hide'}
                        key={`${item.enname}${index}`}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                        label={item.zhname}
                    >
                        <Radio.RadioGroup
                            key={`${item.enname}${index}`}
                            {
                            ...getFieldProps(`${item.enname}`, {
                                initialValue: childRowData[item.enname] || 1,
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            }
                            )}
                        >
                            {
                                item.options && item.options.map((itemoption, index) => {
                                    return (
                                        <Radio
                                            disabled={!item.edit}
                                            key={index} value={itemoption.key}>{itemoption.value}</Radio>
                                    )
                                })
                            }
                        </Radio.RadioGroup>
                        <FormError errorMsg={getFieldError(`${item.enname}`)} />
                    </FormItem>);
                    break;
                default: break;
            }
        })
        return dom;
    }


    render() {
        const _this = this;
        let { form, editModelVisible, btnFlag } = _this.props;
        let btns = _this.onHandleBtns(btnFlag);


        return (

            <PopDialog
                show={editModelVisible}
                title={titleArr[btnFlag]}
                size='lg'
                btns={btns}
                autoFocus={false}
                enforceFocus={false}
                close={this.onCloseEdit}
                className="single-table-pop-model"
            >


                <FormList size="md">
                    {_this.renderFunc()}
                </FormList>

            </PopDialog>
        )
    }
}

export default FormList.createForm()(PopupModal);
